#include "CyGUIButton.h"
#include "CyRoutine.h"
using namespace std;

CyGUIButton::CyGUIButton(HWND parentHWND, INT id)
{
	_id = id;
	_hwnd = GetDlgItem(parentHWND, id);
	_clickHandler = NULL;
	if (_hwnd == 0)
	{
		CY_THROW("Cannot find the button");
	}
	CyMessageProcessor::AddFilter(this);
}

CyGUIButton::~CyGUIButton(void)
{
	CyMessageProcessor::RemoveFilter(this);
	if (_clickHandler != NULL)
		delete _clickHandler;
}

void CyGUIButton::SetText(const std::wstring& str)
{
	SetWindowText(_hwnd, str.c_str());
}

wstring& CyGUIButton::GetText(wstring& str) const
{
	UINT l = GetWindowTextLength(_hwnd);
	WCHAR* buffer = new WCHAR[l+1];
	GetWindowText(_hwnd, buffer, l+1);
	str = buffer;
	delete []buffer;
	return str;
}

BOOL CyGUIButton::HandleMessage(HWND hWnd,
	UINT message, WPARAM wParam, LPARAM lParam)
{
	// dispatch message
	INT wmId = LOWORD(wParam);
	if (message == WM_COMMAND && wmId == _id && _clickHandler != NULL )
	{
		return _clickHandler->Do(hWnd, message, wParam, lParam);
	}
	return FALSE;
}